// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj

const uniCaptcha = require('uni-captcha')
const uniID = require('uni-id')
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
function handleQueryForJQL(query) {
	let str = '';
	for (let key in query) {
		str += `${key}==${query[key]}&&`;
	}
	return str.slice(0, -2);
}
module.exports = {

	_before: function() { // 通用预处理器

	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	/* 
	method1(param1) {
		// 参数校验，如无参数则不需要
		if (!param1) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 业务逻辑
		
		// 返回结果
		return {
			param1 //请根据实际需要返回值
		}
	}
	*/
	// 设置用户权限
	async handlePermission(params) {
		const uniIdCo = uniCloud.importObject('uni-id-cd')
		let userColletion = uniCloud.database().collection('uni-id-users')
		// 通过url 接口形式
		if (!Object.keys(params).length) {
			params = this.getHttpInfo().body
			params = JSON.parse(params)
		}

		let userInfo = await userColletion.doc(params.id).update({
			role: params.role
		})
		return {
			code: 200,
			data: params,
			msg: ''
		}
	},
	// 用户列表
	async uerList(params = {}) {
		if (this.getHttpInfo()) {
			params = this.getHttpInfo().body;
			params = params ? params : '{}'
			params = JSON.parse(params)
		}
		// let q = handleQueryForJQL(params.query)
		// console.log(q)
		// const dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
		// 	clientInfo: this.getClientInfo()
		// })
		// dbJQL.setUser({ // 指定后续执行操作的用户信息，此虚拟用户将同时拥有传入的uid、role、permission
		// 	uid: 'user-id', // 用户id
		// 	role: ['admin'], // 指定当前执行用户的角色为admin。如果只希望指定为admin身份，可以删除uid和permission字段
		// 	permission: [] // 用户权限
		// })
		// let test = await dbJQL.collection('uni-id-users').where(`${q}`).get()
		// console.log(test, 'dbJQL')
		let db = uniCloud.database().collection('uni-id-users')
		let size = 10
		let page = 1
		if (params && params.size) {
			size = params.size
		}
		if (params && params.page) {
			page = params.page
		}
		// 1 - 1 * 10   0
		// 2-1 *10  10
		let skip = (page - 1) * size
		let query = params.query ? params.query : {};
		let data = {}
		let res = await db.limit(size).skip(skip).where(query).get()
		let total = await db.get()
		return {
			code: 200,
			data: res.data,
			total: total.affectedDocs,
			msg: '',
		}
	},
	// 用于url 获取code
	async createCode(params) {
		if (this.getHttpInfo()) {
			params = this.getHttpInfo().body;
			params = params ? params : '{}'
			params = JSON.parse(params)
		}
		const db = uniCloud.database()
		const verifyCodes = db.collection('opendb-verify-codes')
		const uCode = uniCloud.importObject('uni-captcha-co')
		await uniCaptcha['create']({
			scene: params.scene, //来源客户端传递，表示：使用场景值，用于防止不同功能的验证码混用
			uniPlatform: 'h5',
			deviceId: '12345678910'
		})
		let res = await verifyCodes.where({
			scene: params.scene,
			device_uuid: '12345678910',
			state: 0
		}).limit(1).orderBy('created_date', 'desc').get()
		return {
			code: 200,
			data: res.data[0].code,
			msg: ''
		}
	},
	// 检验token是否有效 返回userInfo
	async checkToken(params) {
		if (this.getHttpInfo()) {
			params = this.getHttpInfo().body;
			params = params ? params : '{}'
			params = JSON.parse(params)
		}
		// 测试token
		let token =
			'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI2NDEyZDdhYWU3NjZiYjI5NzUzMjhlMWQiLCJyb2xlIjpbXSwicGVybWlzc2lvbiI6W10sInVuaUlkVmVyc2lvbiI6IjEuMC4xNiIsImlhdCI6MTcwMTkxNzAyMSwiZXhwIjoxNzAxOTI0MjIxfQ.I1Kr4g-JB2UJ296Ltyc_VYfpKiT5-tn-Jq6XPxCxaNM'
		let res = await uniID.checkToken(params && params.token ? params.token : token)
		return {
			code: res.code === 0 ? 200 : 401,
			data: {
				...res.userInfo,
				...{
					role: res.role
				}
			}
		}
	},
	// 上传图片
	async uploadFile(params) {
		if (this.getHttpInfo()) {
			params = this.getHttpInfo().body;
			params = params ? params : '{}'
			params = JSON.parse(params)
		}
		let result, data
		if (params.dataUrl) {
			params.dataUrl = params.dataUrl.split(',')[1];
			data = Buffer.from(params.dataUrl, 'base64');
		}
		result = await uniCloud.uploadFile({
			fileContent: data,
			cloudPath: params.name
		})

		return {
			code: 200,
			data: result,
			msg: ''
		}
	},
	// 发布文章
	async publish(params) {
		if (this.getHttpInfo()) {
			params = this.getHttpInfo().body;
			params = params ? params : '{}'
			params = JSON.parse(params)
		}
		const db = uniCloud.database()
		let data = {
			...params,
			...{
				date: Date.now()
			}
		}
		let res = await db.collection('publish').add(data)
		return {
			code: 200,
			data: res,
			msg: '发布成功'
		}
	},
	// 获取当前用户的文章列表
	async getNewList(params) {
		if (this.getHttpInfo()) {
			params = this.getHttpInfo().body;
			params = params ? params : '{}'
			params = JSON.parse(params)
		}
		const db = uniCloud.database()
		const {
			userId = ''
		} = params
		let res = await db.collection('publish').where({
			userId
		}).orderBy('date', 'desc').get()
		return {
			code: 200,
			data: res,
			msg: ''
		}
	}
}